package com.ygj.ticketManage.service.impl;

import com.base.common.entity.AllCondition;
import com.base.common.entity.DistributeInfo;
import com.base.common.enums.*;
import com.base.common.json.JsonUtil;
import com.base.common.persistent.dao.*;
import com.base.common.persistent.model.*;
import com.base.common.utils.EasyUtil;
import com.base.common.utils.PushUtils;
import com.cjy.common.bean.Files;
import com.cjy.userReport.service.base.TicketBaseServiceImpl;
import com.ygj.ticketManage.service.TicketManageService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 
 * @author Kevin Colin
 * @datetime 2015年8月10日上午10:15:00
 * 
 */
@Service("ticketManageService")
public class TicketManageServiceImpl extends TicketBaseServiceImpl implements
		TicketManageService {

	@Resource
	private EasyUtil easyUtil;

	@Resource
	private EmployeeCompoundsMapper employeeCompoundsMapper;

	@Resource
	private EmployeeMapper employeeMapper;

	@Resource
	private TerminalMapper terminalMapper;
	
	@Resource
	private TicketMapper ticketMapper;

	@Resource
	private TicketReportMapper ticketReportMapper;

	/**
	 * 添加工单操作记录信息
	 * 
	 * @param sTicket
	 * @param employee
	 */
	public int addReport(Ticket sTicket, Employee employee, int reportStatus,
			int reportCategories) {
		TicketReport ticketReport = new TicketReport();
		ticketReport.setEmployee(new Employee().setId(employee.getId()));
		ticketReport.setTicket(new Ticket().setId(sTicket.getId()));
		ticketReport.setCategories(reportCategories);
		ticketReport.setStatus(reportStatus);
		int result = ticketReportMapper.addTicketReport(ticketReport);
		return result;
	}

	@Override
	public int distributeEmployeeForTicket(String[] ticketIds,
			String[] employeeIds, int categories) {
		int result = 0;
		for (String employeeId : employeeIds) {
			result = addReport(
					(new Ticket()).setId(Integer.valueOf(ticketIds[0])),
					(new Employee()).setId(Integer.valueOf(employeeId.trim())),
					TicketReportStatus.WAIT.getValue(), categories);
		}
		return result;
	}

	@Transactional
	@Override
	public int distributeTickets(String[] ticketIds,
			List<String> distributeInfos) {
		try {
			for (String ticketId : ticketIds) {
				for (String distributeInfoStr : distributeInfos) {
					DistributeInfo distributeInfo = JsonUtil.string2Obejct(
							distributeInfoStr, DistributeInfo.class);
					int employeeId = distributeInfo.getEmployeeId();
					TicketReport ticketReport = new TicketReport();

					// 判断是否有派单权限
					List<Employee> employees = employeeMapper
							.queryEmployeeAndPermissionById(employeeId);

					switch (distributeInfo.getCategories()) {
					case 1:

						List<TicketReport> ticketReports = ticketReportMapper
						.queryTicketReportByticketIdAndReportStatus(
								Integer.valueOf(ticketId.trim()),
								TicketReportStatus.UNTREATED.getValue());
						if (ticketReports.size() == 0) {
							ticketReports = ticketReportMapper
									.queryTicketReportByticketIdAndReportStatus(
											Integer.valueOf(ticketId.trim()),
											TicketReportStatus.TREATMENT.getValue());
						}
						// 更新当前记录状态为已完成
						TicketReport report = ticketReports.get(0);
						// ticketReportMapper.udpateStatusById(report.getId(),
						// TicketReportStatus.PROCESSED.getValue()) ;
						ticketReportMapper.updateReportById(new TicketReport(
								report.getId(), null, null, new Date(),
								TicketReportStatus.PROCESSED.getValue(), null));

						// if (isDispatch) {
						// ticketReport.setCategories(TicketReportCategories.DISPATCH
						// .getValue());
						// } else {
						ticketReport
								.setCategories(TicketReportCategories.EXECUTION
										.getValue());

						// 更新工单状态
						int count = ticketMapper.updateStatusById(
								Integer.valueOf(ticketId.trim()),
								TicketStatus.EXECUTION.getValue());
						System.out.println(count);
						// }

						// 添加新的纪录
						ticketReport.setTicket(new Ticket().setId(Integer
								.valueOf(ticketId.trim())));
						ticketReport.setStatus(TicketReportStatus.UNTREATED
								.getValue());
						ticketReport.setStartTime(new Date());
						ticketReport.setEmployee(new Employee()
								.setId(employeeId));
						ticketReportMapper.addTicketReport(ticketReport);

						// 给员工app发送通知
						List<Terminal> terminals = terminalMapper
								.queryTerminalById(employees.get(0)
										.getTerminal().getId());
						String appleClientId = null;
						String androidClientId = null;
						String mess = null;
						if (terminals.size() > 0) {
							mess = "有新的工单需要您处理，工单号为"
									+ report.getTicket().getCode();
							final String m = mess;
							final String phone = employees.get(0).getPhone()
									.trim();
							// 开启线程延迟
							Thread t = new Thread() {
								@Override
								public void run() {
									easyUtil.sendSms(m, phone);
									try {
										Thread.sleep(10000);
									} catch (InterruptedException e) {
										e.printStackTrace();
									}
								}
							};
							t.start();

							int compounds = 0;
							if(report.getTicket().getCategories() == TicketCategories.REPAIR.getValue() || report.getTicket().getCategories() == TicketCategories.COMPLAINT.getValue()){
								compounds = report.getTicket().getUser().getCompounds().getId();
							} else {
								compounds = employeeCompoundsMapper.queryCompoundsIdById(report.getTicket().getEmployeeCompoundsId());
							}
							
							if(compounds == 0){
								throw new Exception();
							}
							
//							int employeeCompoundsId = employeeCompoundsMapper.queryEmployeeCompoundsIdByEmployeeIdAndCompoundsId(employeeId, compounds);
//							sendSms(mess, phone, clientId, appType, type, smsId, receiveTerminalId, senderTerminalId);
							if (terminals.get(0).getAppleClientId() != null) {
								appleClientId = terminals.get(0)
										.getAppleClientId();
								sendSms(mess, employees.get(0).getPhone(), appleClientId,
										AppType.YGJ.getValue(), SmsType.MAIN.getValue(), 0, terminals.get(0).getId(), 0);
							}

							if (terminals.get(0).getAndroidClientId() != null) {
								androidClientId = terminals.get(0)
										.getAndroidClientId();
								sendSms(mess, employees.get(0).getPhone(), androidClientId,
										AppType.YGJ.getValue(), SmsType.MAIN.getValue(), 0, terminals.get(0).getId(), 0);
							}
						}
						break;

					default:
						addReport((new Ticket()).setId(Integer
								.valueOf(ticketIds[0])),
								(new Employee()).setId(Integer
										.valueOf(employeeId)),
								TicketReportStatus.WAIT.getValue(),
								distributeInfo.getCategories());
						break;
					}
				}
				// List<Authority> authorities = employees.get(0)
				// .getAuthorities();
				// boolean isDispatch = false;
				// for (Authority authority : authorities) {
				// if (PermissionCategories.DISPATCH.getValue().equals(
				// authority.getValue())) {
				// isDispatch = true;
				// break;
				// }
				// }

			}

			return 1;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}

	}

	@Transactional
	@Override
	public int finishTicketByMySelf(String[] ticketIds, String report,
			Files files, String basePath) {
		try {
			for (String ticketId : ticketIds) {

				// 查询当前记录
				TicketReport ticketReport = ticketReportMapper
						.queryTicketReportByticketIdAndReportStatus(
								Integer.valueOf(ticketId.trim()),
								TicketReportStatus.UNTREATED.getValue()).size() == 0 ? ticketReportMapper
						.queryTicketReportByticketIdAndReportStatus(
								Integer.valueOf(ticketId.trim()),
								TicketReportStatus.TREATMENT.getValue()).get(0)
						: ticketReportMapper
								.queryTicketReportByticketIdAndReportStatus(
										Integer.valueOf(ticketId.trim()),
										TicketReportStatus.UNTREATED.getValue())
								.get(0);
				int reportCategories = ticketReport.getCategories();

				// 保存图片
				String sysImagesFile = "/resources/images/tickets/"
						+ ticketReport.getTicket().getCode().trim() + "/report";
				String[] fileNames = files.getFileFileName();
				String picUrls = "";
				if (fileNames != null && fileNames.length != 0) {
					picUrls = easyUtil.savePictures(files.getFile(), basePath,
							sysImagesFile, fileNames, picUrls);
				}

				// 更新当前记录
				ticketReportMapper.updateReportById(new TicketReport(
						ticketReport.getId(), report, null, new Date(),
						TicketReportStatus.PROCESSED.getValue(), picUrls));

				// 根据当前记录类型对应操作
				switch (reportCategories) {
				case 1:
					// 更新工单记录状态，发送短信通知
					updateNextReport(ticketId,
							TicketReportCategories.CHECKING.getValue());

					// 更新工单状态
					ticketMapper.updateStatusById(
							Integer.valueOf(ticketId.trim()),
							TicketStatus.CHECKING.getValue());
					break;
				case 2:
					// 更新工单记录状态，发送短信通知
					updateNextReport(ticketId,
							TicketReportCategories.SUPERVISION.getValue());
					break;
				case 3:
					// 更新工单记录状态，发送短信通知
					updateNextReport(ticketId,
							TicketReportCategories.RETURNVISIT.getValue());

					// 更新工单状态
					ticketMapper.updateStatusById(
							Integer.valueOf(ticketId.trim()),
							TicketStatus.RETURNVISIT.getValue());
					break;
				case 4:
					// 更新工单状态
					ticketMapper.updateStatusById(
							Integer.valueOf(ticketId.trim()),
							TicketStatus.FINISH.getValue());

					// 给业主发送工单完成提醒
					// 判断是业主提交还是员工提交
					if (ticketReport.getTicket().getUser() != null) {
						List<Terminal> terminals = terminalMapper
								.queryTerminalByPhoneRegisted(ticketReport
										.getTicket().getSubUserPhone(),
										AppType.CJY.getValue());
						String appleClientId = null;
						String androidClientId = null;
						String mess = null;
						if (terminals.size() > 0) {
							mess = "您的工单已完成，请评价，工单号为："
									+ ticketReport.getTicket().getCode();
							easyUtil.sendSms(mess, ticketReport.getTicket()
									.getSubUserPhone());
//							sendSms(mess, phone, clientId, appType, type, smsId, receiveTerminalId, senderTerminalId);
							if (terminals.get(0).getAppleClientId() != null
									&& terminals.get(0).getAppleClientId()
											.trim() != "") {
								appleClientId = terminals.get(0)
										.getAppleClientId();
								sendSms(mess, ticketReport.getTicket().getSubUserPhone(), 
										appleClientId, AppType.CJY.getValue(),
										SmsType.MAIN.getValue(), 0, terminals.get(0).getId(), 0);
							}

							if (terminals.get(0).getAndroidClientId() != null
									&& terminals.get(0).getAndroidClientId()
											.trim() != "") {
								androidClientId = terminals.get(0)
										.getAndroidClientId();
								sendSms(mess, ticketReport.getTicket().getSubUserPhone(), 
										androidClientId, AppType.CJY.getValue(),
										SmsType.MAIN.getValue(), 0, terminals.get(0).getId(), 0);
							}
						}
					} else {
						// 判断工单类别是否是内部投诉
						if (ticketReport.getTicket().getCategories() == TicketCategories.EMPLOYEECOMLAINT
								.getValue()) {
							List<Terminal> terminals = terminalMapper
									.queryTerminalByPhoneRegisted(ticketReport
											.getTicket().getSubUserPhone(),
											AppType.YGJ.getValue());
							String appleClientId = null;
							String androidClientId = null;
							String mess = null;
							if (terminals.size() > 0) {
								mess = "您的工单已完成，请评价，工单号为："
										+ ticketReport.getTicket().getCode();
								easyUtil.sendSms(mess, ticketReport.getTicket()
										.getSubUserPhone());
								if (terminals.get(0).getAppleClientId() != null
										&& terminals.get(0).getAppleClientId()
												.trim() != "") {
									appleClientId = terminals.get(0)
											.getAppleClientId();
//									sendSms(mess, phone, clientId, appType, type, smsId, receiveTerminalId, senderTerminalId);
									sendSms(mess, ticketReport.getTicket().getSubUserPhone(),
											appleClientId, AppType.YGJ.getValue(),
											SmsType.MAIN.getValue(), 0, terminals.get(0).getId(), 0);
								}

								if (terminals.get(0).getAndroidClientId() != null
										&& terminals.get(0)
												.getAndroidClientId().trim() != "") {
									androidClientId = terminals.get(0)
											.getAndroidClientId();
									sendSms(mess, ticketReport.getTicket().getSubUserPhone(),
											androidClientId, AppType.YGJ.getValue(),
											SmsType.MAIN.getValue(), 0, terminals.get(0).getId(), 0);
								}
							}
						}
					}
					return 1;
				default:
					return 0;
				}

			}
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	@Transactional
	@Override
	public int getTicketByMySelf(String[] ticketIds) {
		try {
			for (String ticketId : ticketIds) {

				// 更新当前记录状态为处理中
				TicketReport report = ticketReportMapper
						.queryTicketReportByticketIdAndReportStatus(
								Integer.valueOf(ticketId.trim()),
								TicketReportStatus.UNTREATED.getValue()).get(0);
				ticketReportMapper.udpateStatusById(report.getId(),
						TicketReportStatus.TREATMENT.getValue());
			}
			return 1;
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
	}

	@Override
	public List<Ticket> getTicketsByCategoriesAndStatus(int employeeId,
			AllCondition allCondition) {
		return ticketMapper.queryTicketsByEmployeeIdAndReportCategories(
				employeeId, allCondition.getReportCategories(), allCondition.getTicketCategories(), allCondition.getBeginTime(), allCondition.getEndTime(), allCondition.getStatus(), getStartNum(allCondition.getPage()),
				getEndNum(allCondition.getPage()));
	}

	@Override
	public int getTicketsPagesByEmployeeIdAndReportCategoriesAndReportStatus(
			int employeeId, AllCondition allCondition) {
		int totalTicketsCounts = ticketMapper
				.queryTicketCountsByEmployeeIdAndReportCategories(employeeId,
						allCondition.getReportCategories(), allCondition.getTicketCategories(), allCondition.getBeginTime(), allCondition.getEndTime(), allCondition.getStatus());
		// int totalPages = (totalTicketsCounts % 15 == 0) ? (totalTicketsCounts
		// / 15) : (totalTicketsCounts / 15 + 1);
		return totalTicketsCounts;
	}

	/**
	 * 
	 * @param mess
	 * @param phone
	 * @param clientId
	 * @param appType
	 * @param type
	 * @param smsId
	 * @param receiveTerminalId
	 * @param senderTerminalId
	 */
	public void sendSms(String mess, String phone, 
			String clientId, int appType, int type, int smsId, int receiveTerminalId, int senderTerminalId) {
		Sms sms = easyUtil.addSms(SmsCategories.STSTEMNOTIFIER.getValue(),
				SmsCategories.STSTEMNOTIFIER.getName(), mess, 
				phone, type, smsId, receiveTerminalId, senderTerminalId);

		try {
			System.out.println(PushUtils.pushtoSingle(clientId,
					JsonUtil.dto2String(sms), appType));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 更新下一步记录
	 * 
	 * @param ticketId
	 * @param reportStatus
	 *            下一步工单状记录态
	 */
	public void updateNextReport(String ticketId, int reportCategories) {
		TicketReport tReport;
		tReport = ticketReportMapper
				.queryTicketReportByTicketIdAndReportStatusAndReportCategories(
						Integer.valueOf(ticketId.trim()),
						TicketReportStatus.WAIT.getValue(), reportCategories)
				.get(0);
		ticketReportMapper.updateReportById(new TicketReport(tReport.getId(),
				null, new Date(), null,
				TicketReportStatus.UNTREATED.getValue(), null));
		easyUtil.sendSms("您有新的工单需要处理，工单号为：" + tReport.getTicket().getCode(),
				tReport.getEmployee().getPhone());
	}

}
